import {
  Button,
  Descriptions,
  Input,
  InputNumber,
  message,
  Table,
  Tooltip,
} from "antd";
import Layout from "../Shared/Layout";
import React, { useCallback, useEffect, useState } from "react";
import { request } from "../../Api/api";
import MyButton from "../../Components/MyButton";
import SelectQuestion from "../../Components/Operation/Exam/SelectQuestion";

const TestPaperDetil = () => {
  const [testPaper, setTestPaper] = useState({});
  const [updatingTestPaper, setUpdatingTestPaper] = useState({});
  const [isUpdating, setIsUpdating] = useState(false);
  const [open, setOpen] = useState(false);
  var maxNo = 0;
  const id = new URLSearchParams(window.location.search).get("id");
  const bind = useCallback(async () => {
    const res = await request("/testpaper/detail", { id }, "GET");
    if (res.code >= 0) {
      setTestPaper(res.data);
    }
  }, [id]);
  useEffect(() => {
    async function fetchData() {
      await bind();
    }
    fetchData();
  }, [bind]);
  const items = [
    {
      label: "名称",
      children: (
        <>
          {!isUpdating ? (
            testPaper.name
          ) : (
            <Input
              value={updatingTestPaper.name}
              onChange={(e) =>
                setUpdatingTestPaper({
                  ...updatingTestPaper,
                  name: e.target.value,
                })
              }
            />
          )}
        </>
      ),
    },
    {
      span: 2,
      label: "描述",
      children: (
        <>
          {!isUpdating ? (
            testPaper.explain
          ) : (
            <Input
              value={updatingTestPaper.explain}
              onChange={(e) => {
                console.log(e.target.value);
                setUpdatingTestPaper({
                  ...updatingTestPaper,
                  explain: e.target.value,
                });
              }}
            />
          )}
        </>
      ),
    },
    { label: "作者", children: testPaper.author },
    {
      label: "考试时长",
      children: (
        <>
          {!isUpdating ? (
            testPaper.examTime?.split(":")[0] +
            "小时" +
            testPaper.examTime?.split(":")[1] +
            "分钟"
          ) : (
            <>
              <InputNumber
                value={parseInt(updatingTestPaper.examTime?.split(":")[0])}
                onChange={(e) => {
                  setUpdatingTestPaper({
                    ...updatingTestPaper,
                    examTime:
                      e + ":" + updatingTestPaper.examTime?.split(":")[1],
                  });
                }}
              ></InputNumber>
              小时
              <InputNumber
                value={parseInt(updatingTestPaper.examTime?.split(":")[1])}
                onChange={(e) => {
                  setUpdatingTestPaper({
                    ...updatingTestPaper,
                    examTime:
                      updatingTestPaper.examTime?.split(":")[0] + ":" + e,
                  });
                }}
              ></InputNumber>
              分钟
            </>
          )}
        </>
      ),
    },
    {
      label: "总分",
      children: (
        <>
          {!isUpdating ? (
            testPaper.sumPoint
          ) : (
            <InputNumber
              value={updatingTestPaper.sumPoint}
              onChange={(e) =>
                setUpdatingTestPaper({
                  ...updatingTestPaper,
                  sumPoint: e,
                })
              }
            ></InputNumber>
          )}
        </>
      ),
    },
    {
      label: "及格分",
      children: (
        <>
          {!isUpdating ? (
            testPaper.passPoint
          ) : (
            <InputNumber
              value={updatingTestPaper.passPoint}
              onChange={(e) =>
                setUpdatingTestPaper({
                  ...updatingTestPaper,
                  passPoint: e,
                })
              }
            ></InputNumber>
          )}
        </>
      ),
    },
    {
      label: "创建时间",
      children: new Date(testPaper.createTime).toLocaleString(),
    },
  ];
  const columns = [
    { title: "第几题", dataIndex: "no", width: 100, ellipsis: true },
    {
      title: "题目",
      dataIndex: "questionContent",
      width: isUpdating ? 700 : 900,
      ellipsis: true,
      render: (_, { questionContent }) => {
        return (
          <Tooltip
            title={questionContent.split("h").map((d, i) => (
              <p key={i}>{d}</p>
            ))}
            placement="topLeft"
          >
            <span title="">{questionContent}</span>
          </Tooltip>
        );
      },
    },
    {
      title: "分值",
      dataIndex: "point",
      width: 100,
      ellipsis: true,
      render: (_, { point, id }) => {
        return !isUpdating ? (
          point
        ) : (
          <InputNumber
            value={point}
            onChange={(e) => {
              setUpdatingTestPaper({
                ...updatingTestPaper,
                testPaperDetails: updatingTestPaper.testPaperDetails.map(
                  (d) => {
                    if (d.id === id) {
                      return {
                        ...d,
                        point: e,
                      };
                    }
                    return d;
                  }
                ),
              });
            }}
          ></InputNumber>
        );
      },
    },
    isUpdating
      ? {
          title: "操作",
          dataIndex: "operation",
          width: 100,
          ellipsis: true,
          render: (_, { id }) => (
            <MyButton
              type={"danger"}
              onClick={() => {
                setUpdatingTestPaper({
                  ...updatingTestPaper,
                  testPaperDetails: updatingTestPaper.testPaperDetails.filter(
                    (d) => d.id !== id
                  ),
                });
              }}
            >
              移除
            </MyButton>
          ),
        }
      : { width: 0 },
  ];
  const toggleUpdating = () => {
    if (!isUpdating) {
      setUpdatingTestPaper({ ...testPaper });
    }
    setIsUpdating(!isUpdating);
  };
  const isChanged = () => {
    return JSON.stringify(testPaper) !== JSON.stringify(updatingTestPaper);
  };
  const updateTestPaper = async () => {
    if (updatingTestPaper.name === "") {
      message.error("试卷名称不能为空");
      return;
    }
    if (updatingTestPaper.examTime === "") {
      message.error("考试时长不能为空");
      return;
    }
    if (updatingTestPaper.passPoint === "") {
      message.error("及格分不能为空");
      return;
    }
    if (updatingTestPaper.sumPoint === "") {
      message.error("总分不能为空");
      return;
    }
    if (updatingTestPaper.testPaperDetails.length === 0) {
      message.error("试卷题目不能为空");
      return;
    }
    var sp = 0;
    var flag = true;
    updatingTestPaper.testPaperDetails.forEach((d) => {
      if (d.point == null || d.point === 0) {
        flag = false;
      }
      sp += d.point;
    });
    if (!flag) {
      message.error("试卷题目分值不能为空或为零");
      return;
    }
    if (updatingTestPaper.sumPoint !== sp) {
      message.error("总分与各题分值之和不相等，请检查");
      return;
    }
    const res = await request(
      "/testpaper/update",
      {
        id: id,
        name: updatingTestPaper.name,
        explain: updatingTestPaper.explain,
        examTime: updatingTestPaper.examTime,
        sumPoint: updatingTestPaper.sumPoint,
        passPoint: updatingTestPaper.passPoint,
        testPaperDetails: updatingTestPaper.testPaperDetails,
      },
      "POST"
    );
    if (res.code >= 0) {
      message.success(res.message);
      setIsUpdating(false);
      bind();
    } else {
      message.error(res.message);
    }
  };
  const showAddQuestionModal = () => {
    // TODO: 打开添加题目弹窗
    setOpen(true);
  };
  const addQuestion = (questions) => {
    // TODO: 添加题目
    maxNo = updatingTestPaper.testPaperDetails.length;
    setUpdatingTestPaper({
      ...updatingTestPaper,
      testPaperDetails: [
        ...updatingTestPaper.testPaperDetails,
        ...questions
          .filter(
            (d) =>
              !updatingTestPaper.testPaperDetails
                .map((e) => e.id)
                .includes(d.id)
          )
          .map((d) => {
            return {
              id: maxNo + 1,
              no: ++maxNo,
              questionContent: d.content,
              questionId: d.id,
              point: 0,
            };
          }),
      ],
    });
    setOpen(false);
  };
  return (
    <Layout>
      {
        <>
          <SelectQuestion
            open={open}
            onCancel={() => {
              setOpen(false);
            }}
            onOk={addQuestion}
          ></SelectQuestion>
          <Descriptions
            title="试卷详情"
            items={items}
            layout="vertical"
            bordered={true}
            column={4}
            extra={
              !isUpdating ? (
                <MyButton type={"warning"} onClick={toggleUpdating}>
                  修改
                </MyButton>
              ) : (
                <>
                  <MyButton onClick={toggleUpdating}>取消</MyButton>
                  {
                    <Button
                      disabled={!isChanged()}
                      type={"primary"}
                      onClick={updateTestPaper}
                    >
                      保存
                    </Button>
                  }
                </>
              )
            }
          ></Descriptions>
          {!isUpdating ? null : (
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <MyButton
                type={"success"}
                style={{ marginRight: "10px" }}
                onClick={showAddQuestionModal}
              >
                添加
              </MyButton>
            </div>
          )}
          <Table
            dataSource={
              !isUpdating
                ? testPaper.testPaperDetails
                : updatingTestPaper.testPaperDetails
            }
            columns={columns}
            pagination={false}
            rowKey={({ id }) => id}
          ></Table>
        </>
      }
    </Layout>
  );
};

export default TestPaperDetil;
